package com.tqyan.dal.sharding;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashAlgorithmUtil {

    public static long hash(String paramValue, Integer number) {
        long hashCode = HashAlgorithm.KETAMA_HASH.hash(computeMd5(paramValue), 0);
        long index = hashCode % number;
        return Math.abs(index);
    }

    public static BigInteger mod(BigInteger key, BigInteger length) {
        return key.mod(length);
    }

    public static byte[] computeMd5(String k) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            md5.update(k.getBytes(StandardCharsets.UTF_8));
            return md5.digest();
        } catch (NoSuchAlgorithmException var2) {
            throw new RuntimeException("MD5 not supported", var2);
        }
    }

    public enum HashAlgorithm {
        KETAMA_HASH;
        HashAlgorithm() {}
        public long hash(byte[] digest, int nTime) {
            long rv = (long) (digest[3 + nTime * 4] & 255) << 24
                    | (long) (digest[2 + nTime * 4] & 255) << 16
                    | (long) (digest[1 + nTime * 4] & 255) << 8
                    | (long) (digest[nTime * 4] & 255);
            return rv & 4294967295L;
        }
    }

    public static void main(String[] args) {
        int size = 64;
        System.out.println(hash("IFF211119113454940423619", size));
        System.out.println(hash("FC0012000089", size));
    }

}


